package com.zenithsun.news.specialnews.dao.impl;

import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.CriteriaSpecification;
import org.springframework.stereotype.Repository;
import com.syzg.common.dao.impl.BaseDAOHibernate;
import com.zenithsun.news.specialnews.dao.SpecialnewsDAO;
import com.zenithsun.news.specialnews.model.Specialnews;

@Repository("specialnewsDao")
public class SpecialnewsDAOImpl extends BaseDAOHibernate<Specialnews> implements SpecialnewsDAO {

	@Override
	protected Class<Specialnews> getEntityClass() {
		return Specialnews.class;
	}

	@Override
	public void updateNews(String specialNewsId, String[] newsIds) {
		StringBuffer sb = new StringBuffer();
		sb.append("('1'");
		for(String id : newsIds){
			sb.append(",'");
			sb.append(id);
			sb.append("'");
		}
		sb.append(")");
		String sql = String.format("update newsinfo set sn_id='%s'where id in%s",specialNewsId,sb.toString());
		executeSql(sql);
	}

	@Override
	public void updateNews4Edit(String specialNewsId, String[] newsIds) {
		String sql = String.format("update newsinfo set sn_id=null where sn_id='%s'", specialNewsId);
		executeSql(sql);
		updateNews(specialNewsId,newsIds);
	}
	
	@Override
	public int getSpecialNewsCount(Specialnews sn) {
		String sql = "select count(ID) totalCount from specialnews S";
		SQLQuery query=getSession().createSQLQuery(getCondition(sql,sn));
		Long count= Long.parseLong(query.uniqueResult().toString());
		return count.intValue();
	}
	
	@Override
	public List<HashMap<String, Object>> findObjectsList(int pageNo, int limit, Specialnews sn){
		// TODO Auto-generated method stub
		String sql = "select * from specialnews S";
		SQLQuery query=getSession().createSQLQuery(getCondition(sql,sn));
		query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
		@SuppressWarnings("unchecked")
		List<HashMap<String, Object>> list = query.list();
		return list;
	}
	
	private String getCondition(String sql,Specialnews searchCondition){
		StringBuffer sb=new StringBuffer();
		sb.append(" WHERE 1=1 ");
		if(StringUtils.isNotBlank(searchCondition.getTitle())){
			sb.append(" AND S.title like '%").append(searchCondition.getTitle()).append("%'");
		}
		if(sb.length()==0){
			return "";
		}else{
			sb.insert(0, sql);
		}
		sb.append(" ORDER BY CREATE_TIME DESC");
		return sb.toString();
	}
}
